package com.diancan.modules.admin.admin;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.diancan.common.Result;
import com.diancan.domain.Lbt;
import com.diancan.modules.admin.lbt.LbtService;
import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.UUID;

@RestController
@RequestMapping("adminLbt")
@CrossOrigin
public class AdminLbtController {
    @Value("${file.location}")
    String filelocation;
    @Value("${file.path}")
    String filepath;
    @Value("${file.domainName}")
    String domainName;

    private final LbtService lbtService;

    public AdminLbtController(LbtService lbtService) {
        this.lbtService = lbtService;
    }

    // 文件上传
    @PostMapping("fileUpload")
    @SneakyThrows
    public Result fileUpload(MultipartFile file) {
        if (file == null || file.isEmpty()) {
            return Result.buildFailureResult("请传入文件");
        } else {
            // 生成文件名
            String officialSealFileName = UUID.randomUUID().toString().replace("-", "").substring(0, 16) +
                    file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
            // 设置文件保存路径
            String officialSealFilePath = filelocation + "lbt";
            // 创建路径 可以事先手动创建好
            Files.createDirectories(Paths.get(officialSealFilePath));
            // 保存文件
            file.transferTo(Path.of(officialSealFilePath, officialSealFileName));
            // 返回 url
            return Result.buildSuccessResult(domainName + "lbt/" + officialSealFileName);
        }
    }

    // 获取轮播图列表
    @GetMapping("getLbt")
    public Result getLbt() {
        QueryWrapper<Lbt> wrapper = new QueryWrapper<>();
        wrapper.orderByDesc("id");
        return Result.buildSuccessResult(lbtService.list(wrapper));
    }

    // 添加轮播图
    @PostMapping("add")
    public Result addLbt(@RequestBody Lbt lbt) {
        return Result.buildSuccessResult(lbtService.save(lbt));
    }

    // 修改轮播图
    @PostMapping("update")
    public Result updateLbt(@RequestBody Lbt lbt) {
        return Result.buildSuccessResult(lbtService.updateById(lbt));
    }

    // 删除
    @GetMapping("delete")
    public Result deleteLbt(Integer id) {
        return Result.buildSuccessResult(lbtService.removeById(id));
    }
}
